package com.sunny.ynhz.api.subscriber;

import android.app.Activity;
import android.content.Context;
import android.widget.TextView;

import com.sunny.ynhz.error.ApiException;
import com.sunny.ynhz.error.HttpError;
import com.sunny.ynhz.utils.ToastUtils;

import java.lang.reflect.Type;

import rx.Observable;
import rx.Subscriber;

/**
 * Created by Administrator on 2016-10-11.
 */
public class ApiSubscriber extends Subscriber {

    HttpOnResultListener httpOnNextListener;
    private TextView load_data_tv;
    static Observable observable;
    public Activity context;
    private Type type;
    @SuppressWarnings("unchecked")
    public abstract static class HttpOnResultListener<T> {
        public abstract void onNext(T t);

        public void onError(Throwable e) {
        }

        public abstract void onCompleted();

        public abstract void onstart();
    }
    public ApiSubscriber(Context context, HttpOnResultListener httpOnNextListener) {
        this.context = (Activity) context;
        this.httpOnNextListener = httpOnNextListener;
    }

    @Override
    public void onError(Throwable e) {

        try {
            String message = e.getMessage();
            if (message.startsWith("--")) {
                ToastUtils.SingleToastUtil(context, message.replace("--",""));
            }
            else {
                ApiException apiException = HttpError.handleException(e);
                ToastUtils.SingleToastUtil(context,apiException.message);
            }
            httpOnNextListener.onError(e);
        } catch (Exception e1) {
            httpOnNextListener.onError(e1);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        httpOnNextListener.onstart();

    }

    @Override
    public void onCompleted() {
        httpOnNextListener.onCompleted();

    }

    @Override
    public void onNext(Object t) {
        httpOnNextListener.onNext(t);
    }


}
